var express = require('express');
var router = express.Router();

let commonDao = require('../dao/commonDao');
let code = require('../constant/code');
const fs = require('fs');
const crypto = require('crypto');
const moment = require('moment');

// const uploadService = require('../services/uploadService');
// const upload = uploadService.upload();


/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', {
    title: 'Express'
  });
});


router.post('/login', function (req, res, next) {

  // utils.fileLog(ip, 'login');

  let body = req.body;
  if (!body.account || !body.password) {
    res.send({
      code: code.REQUEST_DATA_ERROR
    });
    return;
  }

  let password = crypto.createHash('md5').update(body.password, "utf-8").digest('hex');
  commonDao.findOneData("adminModel", {
    account: body.account,
    password: password
  }, function (err, result) {
    if (!!err) {
      res.send({
        code: err
      });
    } else {
      if (!result) {
        // 帐号密码错误
        res.send({
          code: code.ACCOUNT_OR_PASSWORD_ERROR
        });
      } else {
        req.session.uid = result.uid;
        req.session.permission = result.permission;
        res.send({
          code: code.OK,
          msg: {
            userData: result._doc
          }
        });
      }
    }
  })
});


router.post('/logout', function (req, res) {
  req.session.uid = "";
  req.session.permission = 0;
  res.send({
    code: code.OK
  });
});


// router.post('/uploadFile', upload.single('file'), function (req, res, next) {

//   if (req.file) {
//     let filePath = req.file.destination + '/' + req.file.filename;
//     filePath = filePath.replace(/.\/public/, '');
//     res.send({ code: 0, filePath });
//   } else {
//     res.send({ code: -1 });
//   }

// });

router.post('/upload', function (req, res, next) {

  if (req.body.file) {

    let data = req.body.file;
    let base64 = data.replace(/^data:image\/\w+;base64,/, "");
    base64 = base64.replace(/_/g, '/').replace(/-/g, '+');
    let dataBuffer = Buffer.from(base64, 'base64');

    let filePath = '/uploadcache/';
    let chars = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'P', 'R', 'T', 'W', 'Y', 'M', "N", 'V', 'X', 'Z', 'S'];
    let randomChar = '';
    for (let i = 0; i < 5; i++) {
      let number = Math.floor(Math.random() * chars.length);
      randomChar = randomChar + chars[number];
    }
    let pngName = randomChar + moment().format('X') + '.jpg';
    filePath += pngName;
    let savePath = './public/uploadcache/' + pngName;
    fs.writeFile(savePath, dataBuffer, function (err) {
      if (!err) {
        res.send({ code: 0, filePath });
      } else {
        res.send({ code: -1 });
      }
    })
  } else {
    res.send({ code: -1 });
  }

});

module.exports = router;